import datetime
import webapp2
from google.appengine.ext.webapp.util import run_wsgi_app

class ChatMessage(object):
    def __inti__(self, user, msg):
        self.user = user
        self.message = msg
        self.time = datetime.datetime.now()

    def __str__(self):
        return "%s (%s): %s" % (self.user, self.time, self.message)

Messages = []

class ChatRoomPage(webapp2.RequestHandler):
    #Messages = []

    def get(self):
        self.response.headers["Content-Type"] = "text/html"
        self.response.out.write("""
            <html>
                <head>
                    <title>Wayn's chatroom</title>
                </head>

                <body>
                    <h1>Welcome to wayne's chatroom</h1>
                    <p>Current time: %s</p>
            """ % (datetime.datetime.now()))

        # out all messages
        global Messages
        for msg in Messages:
            self.response.out.write("<p>%s</p>" % msg)
        self.response.out.write("""
            <form action = "" method = "post">
            <div><b>Name:</b>
            <textarea name = "name" rows = "1" cols = "25"></textarea></div>
            <p><b>Message</b></p>
            <div><textarea name = "message" rows = "5" cols = "60"></textarea></div>
            <div><input type = "submit" value = "send message"</input></div>
            </form>
        </body>
    </html>
    """)


    def post(self):
        chatter = self.request.get("name")
        msg = self.request.get("message")
        global Messages
        Messages.append(ChatMessage(chatter, msg))
        self.redirect('/')


chatapp = webapp2.WSGIApplication([('/', ChatRoomPage)])

def main():
    run_wsgi_app(chatapp)

if __name__ == "__main__":
    main()
